import threading
import time
import random

class StopAndWait:
    def __init__(self):
        self.packet_loss_prob = 0.3  # 丢包概率
        self.is_running = True
        self.ack_received = False

    def sender(self):
        seq_num = 0
        while self.is_running:
            # 发送数据包
            print(f"甲方发送数据包，序号：{seq_num}")
            # 模拟丢包
            if random.random() > self.packet_loss_prob:
                threading.Thread(target=self.receiver, args=(seq_num,)).start()
            else:
                print("甲方数据包丢失...")
            # 等待确认
            self.ack_received = False
            start_time = time.time()
            while not self.ack_received and time.time() - start_time < 3:
                time.sleep(0.1)
            if not self.ack_received:
                print("甲方超时，重传数据包，序号：{seq_num}")
                threading.Thread(target=self.receiver, args=(seq_num,)).start()
                self.ack_received = False
                time.sleep(1)
            else:
                seq_num = 1 - seq_num  # 切换序号
            time.sleep(1)

    def receiver(self, seq_num):
        # 模拟接收并返回确认
        print(f"乙方收到数据包，序号：{seq_num}，返回确认")
        # 模拟丢包
        if random.random() > self.packet_loss_prob:
            self.ack_received = True
            print("乙方确认已发送")
        else:
            print("乙方确认丢失...")

    def start(self):
        threading.Thread(target=self.sender).start()
        # 运行一段时间后停止
        time.sleep(10)
        self.is_running = False

if __name__ == "__main__":
    saw = StopAndWait()
    saw.start()